<template>
  <div>
    <el-card>
      <!-- 提示区 -->
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      />
      <!-- 进度条 -->
      <el-steps
        :space="200"
        :active="active - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息" />
        <el-step title="商品参数" />
        <el-step title="商品属性" />
        <el-step title="商品图片" />
        <el-step title="商品内容" />
        <el-step title="完成" />
      </el-steps>
      <!-- tabs区域 -->
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          v-model="active"
          :tab-position="'left'"
          :before-leave="beforeTableave"
          @tab-click="huan"
          class="demo-tabs"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="ruleForm.goods_name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model.number="ruleForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model.number="ruleForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model.number="ruleForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="">
              <el-cascader
                v-model="ruleForm.goods_cat"
                :options="shuju.onject"
                :props="shijian"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染表单 -->
            <el-form-item
              :label="item.attr_name"
              v-for="item in shuju.arr"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  :label="cd"
                  v-for="(cd, i) in item.attr_vals"
                  :key="i"
                  border
                /> </el-checkbox-group
            ></el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              :label="item.attr_name"
              v-for="item in shuju.ajj"
              :key="item.attr_id"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action图片上传到后台api的地址 -->
            <el-upload
              :action="url"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="handerstoken"
              :on-success="postok"
            >
              <el-button type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <div style="border: 1px solid #ccc">
              <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
              />
              <Editor
                style="height: 300px; overflow-y: hidden"
                v-model="ruleForm.goods_introduce"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
              />
            </div>

            <el-button type="primary" class="buts" @click="add(ruleFormRef)"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog v-model="dialogVisible" title="图片预览" width="50%" class="mc">
      <span>无法预览,后台权限没开</span>
      <img
        class="mcs"
        src="https://img0.baidu.com/it/u=765085334,1024427517&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=495"
        alt=""
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted, computed, shallowRef } from 'vue';
import type { FormInstance, FormRules } from 'element-plus';
import { apis } from '@/http/api';
import { ElMessage } from 'element-plus';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import _ from 'lodash';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
//表单验证
const ruleFormRef = ref<FormInstance>();
//添加商品
const ruleForm = reactive({
  goods_name: '', //商品名称
  goods_price: 0 as number, //商品价格
  goods_weight: 0 as number, //商品重量
  goods_number: 0 as number, //商品数量
  goods_cat: [] as any, //商品所属的分类数组
  pics: [] as any, //图片的数组
  goods_introduce: '',
  attrs: [] as any,
});
const active = ref('0') as any;
//验证条件
const rules = reactive<FormRules>({
  goods_name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { type: 'string', message: '必须输入文字', trigger: 'blur' },
  ],
  goods_price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', message: '必须输入数字', trigger: 'blur' },
  ],
  goods_weight: [
    { required: true, message: '请输入商品重量', trigger: 'blur' },
    { type: 'number', message: '必须输入数字', trigger: 'blur' },
  ],
  goods_number: [
    { required: true, message: '请输入商品数量', trigger: 'blur' },
    { type: 'number', message: '必须输入数字', trigger: 'blur' },
  ],
  // value: [{ required: true, message: '请选择商品分类', trigger: 'blur' },],
});
//总数据条数
const toto = ref(0);
//配置选择器的配置对象
let shijian = {
  value: 'cat_id',
  label: 'cat_name',
  children: 'children',
};
//双向绑定事件
const handleChange = () => {
  if (ruleForm.goods_cat.length !== 3) {
    ruleForm.goods_cat = [];
    ElMessage.error('分类必须为三级!!!');

    return;
  }
};
//tabs页切换
const beforeTableave = (activeName: any, oldActiveName: any) => {
  if (oldActiveName == 0 && ruleForm.goods_cat.length !== 3) {
    ElMessage.error('请先选择商品分类');
    return false;
  }
  active.value = activeName;
};
//tabs换内容
const huan = () => {
  console.log(active.value);

  if (active.value == 1) {
    canshu('many');
  } else if (active.value == 2) {
    canshu('only');
  }
};
//参数数据
const canshu = (val: string) => {
  apis.getfeilei(ids.value, val).then(({ data }) => {
    data.forEach((item: any) => {
      item.attr_vals =
        item.attr_vals.length == 0 ? [] : item.attr_vals.split(',');
    });
    if (active.value == 1) {
      shuju.arr = data;
    } else if (active.value == 2) {
      shuju.ajj = data;
    }

    console.log(data);
  });
};
//计算属性
const ids = computed(() => {
  if (ruleForm.goods_cat.length == 3) {
    return ruleForm.goods_cat[2];
  }
  return null;
});
const shuju = reactive({
  onject: null as any,
  arr: null as any,
  ajj: null as any,
});
const huoqu = () => {
  apis.getcategories().then(({ data }) => {
    shuju.onject = data;
    // console.log(data);
  });
};
// 上传url
const url = ref('http://106.12.150.223:8090/api/private/v1/upload');
onMounted(() => {
  huoqu();
});
//处理图片预览
const handlePreview = (file: any) => {
  urls.value = file.response.data.url;
  console.log(file.response.data);

  dialogVisible.value = true;
};
//处理移除图片操作

const handleRemove = (file: any) => {
  /* 
1.获取将要删除的图片的临时路径
2.从pics数组中,找到这个图片对应的索引值
3.调用数组的splice方法,把图片信息对象,从pics数组中移除
 */
  console.log(file);
  const lujing = file.response.data.tmp_path;
  const i = ruleForm.pics.findIndex((x: any) => {
    x.pic == lujing;
  });
  ruleForm.pics.splice(i, 1);
  console.log(ruleForm.pics);
};
//图片上传token
const handerstoken = ref({
  Authorization: window.sessionStorage.getItem('token'),
});
//图片上传真实路径
const urls = ref('');
//图片上传成功后
const postok = (response: any) => {
  /* 
  1.拼接一个得到的图片信息对象
  2.将图片信息对象push到pic数组中
   */
  const picInfo = { pic: response.data.tmp_path };
  ruleForm.pics.push(picInfo);
};
//图片预览
const dialogVisible = ref(false);
//点击添加
const add = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      const fuzhi = _.cloneDeep(ruleForm);
      fuzhi.goods_cat = fuzhi.goods_cat.join(',');
      //动态
      shuju.arr.forEach((item: any) => {
        const newInfo = {
          attar_id: item.attar_id,
          attar_value: item.attr_vals.join(' '),
        };
        ruleForm.attrs.push(newInfo);
      });
      //静态
      shuju.ajj.forEach((item: any) => {
        const newInfo = {
          attar_id: item.attar_id,
          attar_value: item.attr_vals,
        };
        ruleForm.attrs.push(newInfo);
        console.log(item);
      });
      fuzhi.attrs = ruleForm.attrs;
      apis.posttianjiashangpin(fuzhi).then((data) => {
        console.log(data);
      });
      console.log('成功', fuzhi);
      router.push({ name: 'goods' });
    } else {
      console.log('error submit!');
      return false;
    }
  });
};

//富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
const toolbarConfig = {};
// 内容 HTML
const editorConfig = { placeholder: '请输入内容...' };
const handleCreated = (editor: any) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
//步骤条

// watch(ruleForm, (to, fro) => {
//   console.log(to);
// });
</script>

<style lang="less" scoped>
.el-alert {
  margin: 20px 0 0;
}
.el-alert:first-child {
  margin: 0;
}
.el-steps {
  margin: 15px 0;
}

.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.mcs {
  width: 100%;
}
.buts {
  margin: 15px;
}
</style>
